package com.hinacom.pix.client;

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.model.v25.datatype.CX;
import ca.uhn.hl7v2.model.v25.message.RSP_K23;
import ca.uhn.hl7v2.model.v25.segment.MSH;
import ca.uhn.hl7v2.model.v25.message.QBP_Q21;
import ca.uhn.hl7v2.model.v25.segment.PID;
import ca.uhn.hl7v2.parser.Parser;
import com.hinacom.pix.entity.*;
import com.hinacom.pix.enums.ESex;
import org.apache.log4j.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by fyu on 2016/8/31.
 */
public class PIXConsumer extends BaseClient {
    private static Logger logger = Logger.getLogger(PIXSource.class);

    private static String host;
    private static int port;
    static {
        ResourceBundle bundle = PropertyResourceBundle.getBundle("pix");
        host = bundle.getString("v2-pix-host");
        String pixPort = bundle.getString("v2-pix-port");
        port = Integer.parseInt(pixPort);
        sendingApplicationName = bundle.getString("sending-application-name");
        sendingFacilityName = bundle.getString("sending-facility-name");
        receivingApplicationName = bundle.getString("receiving-application-name");
        receivingFacilityName = bundle.getString("receiving-facility-name");
    }

    private static String sendingApplicationName;
    private static String sendingFacilityName;
    private static String receivingApplicationName;
    private static String receivingFacilityName;

    public String query(PIXQueryParameter queryParameter) throws HL7Exception, ParseException {
        String request = this.bind(queryParameter);
        logger.info("Query Request: " + request);
        String response = this.sendMessage(request);
        logger.info("Query Response: " + response);
        // convert Patient

        // HapiContext context = new DefaultHapiContext();
        // Parser p = context.getGenericParser();
        return response;
    }

    private String bind(PIXQueryParameter queryParameter) throws HL7Exception {
        QBP_Q21 qbp = new QBP_Q21();
        MSH msh = qbp.getMSH();
        this.fillMSH(msh);

        qbp.getQPD().getQpd1_MessageQueryName().getCe1_Identifier().setValue(queryParameter.getIdentifier());
        qbp.getQPD().getQpd2_QueryTag().setValue(queryParameter.getTag());

        PatientIdentifier patientIdentifier = queryParameter.getParametersInsuccessivefields();
        qbp.getQPD().getQpd3_UserParametersInsuccessivefields().parse(patientIdentifier.toString());

        qbp.getRCP().getRcp1_QueryPriority().setValue("I");
        String result = qbp.toString().replace("\r", "\r\n");

        // add search domain, the search domain is not support in the HL7 class library but it is request in test case, so add it in here.
        if(queryParameter.getFilterDomain()!=null)
        {
            StringBuffer sbInputMessage = new StringBuffer();
            String[] sMessageItems = result.split("\r\n");
            for (String messageItem : sMessageItems) {
                sbInputMessage.append(messageItem);
                if(messageItem.startsWith("QPD"))
                {
                    sbInputMessage.append("|^^^");
                    sbInputMessage.append(queryParameter.getFilterDomain().toString());
                }
                sbInputMessage.append("\r\n");
            }
            result = sbInputMessage.toString();
        }
        return result;
    }

    private void fillMSH(MSH msh) throws HL7Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String now = df.format(new Date());
        msh.getMsh1_FieldSeparator().setValue("|");
        msh.getMsh2_EncodingCharacters().setValue("^~\\&");
        msh.getSendingApplication().getNamespaceID().setValue(sendingApplicationName);
        msh.getSendingFacility().getHd1_NamespaceID().setValue(sendingFacilityName);
        msh.getReceivingApplication().getNamespaceID().setValue(receivingApplicationName);
        msh.getReceivingFacility().getHd1_NamespaceID().setValue(receivingFacilityName);

        // generate a random id
        String controlId = UUID.randomUUID().toString().substring(0, 8);
        controlId = String.valueOf(Long.parseLong(controlId, 16));

        msh.getMessageControlID().setValue(String.format("HINA-%s", controlId));
        msh.getDateTimeOfMessage().getTime().setValue(now);
        msh.getMessageType().getMsg1_MessageCode().setValue("QBP");
        msh.getMessageType().getMsg2_TriggerEvent().setValue("Q23");
        msh.getMessageType().getMsg3_MessageStructure().setValue("QBP_Q21");

        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("P");
        msh.getMsh12_VersionID().getVersionID().setValue("2.5");
    }

    @Override
    protected String getHost() {
        return host;
    }

    @Override
    protected int getPort() {
        return port;
    }
}
